package com.stone.framework.core.filter;

import java.lang.reflect.Type;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import com.stone.framework.core.context.UUIDContext;
import com.stone.framework.message.ReqMessage;

@ControllerAdvice
public class ReqMessageAdvice extends RequestBodyAdviceAdapter {

    @Value("${stone.log.req.enabled:true}")
    private boolean enabled = true;

    private static final Logger LOGGER = LoggerFactory.getLogger(ReqMessageAdvice.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
        Class<? extends HttpMessageConverter<?>> converterType) {
        if (ReqMessage.class.isAssignableFrom(methodParameter.getParameterType())) {
            return true;
        }
        return false;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
        Class<? extends HttpMessageConverter<?>> converterType) {
        this.buildUUID(body);
        if (enabled) {
            LOGGER.info("request body: {}", body);
        }
        return body;
    }

    @SuppressWarnings("unchecked")
    private void buildUUID(Object body) {
        if (body instanceof ReqMessage) {
            String uid = ((ReqMessage<Object>)body).getUid();
            UUIDContext.build().set(uid);
        }
    }
}
